package common.spring.base;

import common.pojo.CommonResult;
import common.utils.JsonUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class BaseController implements HandlerExceptionResolver {

    protected Logger logger = LoggerFactory
            .getLogger(this.getClass());

    @ResponseBody
    @ExceptionHandler(MissingServletRequestParameterException.class)
    protected CommonResult missingParameterHandler(
            MissingServletRequestParameterException exception) {
        String paramsName = exception.getParameterName();
        return returnFailsWrapper(String.format("miss request params:%s", paramsName), null);
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    protected CommonResult serverExceptionHandler(
            Exception e) throws IOException {
        logger.error("Error:", e);
        return returnFailsWrapper("服务器处理异常", null);
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e){
        logger.error("Error",e);
        writerTextToBody(response, JsonUtils.toJson(new CommonResult(-1, "服务器处理异常")));
        return new ModelAndView();
    }

    final protected void writerJsonToBody(HttpServletResponse response, Object obj){
        try{
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JsonUtils.toJson(obj));
        }catch (Exception e){
            this.logger.error("Error", e);
        }
    }

    final protected void writerTextToBody(HttpServletResponse response,String text){
        try{
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().write(text);
        }catch (Exception e){
            this.logger.error("Error", e);
        }
    }

    final protected CommonResult returnDataWrapper(Object... obj) {
        return returnSuccessWrapper(obj);
    }

    final protected CommonResult returnWrapper(int code, String message, Object... obj) {
        CommonResult result = new CommonResult();
        result.setMessage(message);
        if (obj != null && obj.length == 1) {
            result.setData(obj[0]);
        } else {
            result.setData(obj);
        }
        result.setCode(code);
        logger.debug(String.format("service return code : %s,message:%s", code, message));
        return result;
    }

    final protected CommonResult returnBoolWrapper(boolean bool, String fails, Object... obj) {
        if (bool) {
            return returnSuccessWrapper(obj);
        }
        return returnFailsWrapper(fails, obj);
    }

    final protected CommonResult returnSuccessWrapper(Object... obj) {
        return returnWrapper(CommonResult.SUCCESS, "success", obj);
    }

    final protected CommonResult returnFailsWrapper(String message, Object... obj) {
        return returnWrapper(CommonResult.FAILS, message, obj);
    }

    /**
     * 解析参数
     * @param request
     * @return
     */
    final protected Map<String,Object> parseRequestParamMap(HttpServletRequest request, boolean convertExtArg) {
        Enumeration<String> argEnu = request.getParameterNames();
        Map<String,Object> args=new HashMap();
        while (argEnu.hasMoreElements()) {
            String argName = argEnu.nextElement();
            String[] value = request.getParameterValues(argName);
            if (value == null) {
                continue;
            }
            for (String v : value) {
                args.put(argName,v);
            }
            if(value.length>1){
                args.put(argName,value);
            }
        }
        if(convertExtArg){
            String start=request.getParameter("start");
            if(StringUtils.isNotBlank(start)){
                String limit=request.getParameter("limit");
                int l= NumberUtils.toInt(limit);
                l=l>0?l:20;
                int s=NumberUtils.toInt(start);
                s=s<0?0:s;
                args.put("curPage",s/l + 1);
                args.put("pageSize",l);
            }
        }
        return args;
    }

}
